package org.zoomdev.zoom.web.test;

public class TimeUtils {

    public static void run(Executor executor, int times) {
        long time = System.currentTimeMillis();
        try {
            for (int i = 0; i < times; ++i) {
                executor.execute();
            }

        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            System.out.printf("======运行次数[%d],时间[%s]====%n", times,
                    getTime(System.currentTimeMillis() - time));
        }
    }

    public static void run(Executor executor) {
        long time = System.currentTimeMillis();
        try {
            executor.execute();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            System.out.printf("======运行时间[%d]毫秒====%n", System.currentTimeMillis() - time);
        }
    }

    private static String getTime(long ms) {
        if (ms > 1000) {
            long second = ms / 1000;
            if (second > 60) {
                return ((double) second / 60) + "分" + (second % 60) + "秒";
            } else {
                return ((double) ms / 1000) + "秒";
            }

        } else {
            return ms + "毫秒";
        }
    }

    public interface Executor {
        void execute() throws Throwable;
    }
}
